<!--用户管理-->
<template>
  <div class="page-container">
    <ex_super_table_page v-bind="option" ref="superTablePage">
    </ex_super_table_page>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="880px" height="200px"
      :close-on-click-modal="false">
      <el-form ref="formEl" :model="formValue" :rules="rules" label-width="120px" class="common-form-panel-div"
        style="padding: 0px 10px;">
        <ex_header_spiler :title="$tt('label_base_info')"></ex_header_spiler>
        <el-row v-if="roleScope != 'DEFAULT'">
          <el-col>
            <el-form-item :label="$tt('label_belong_company')">
              {{ $loginUser.companyName }}
              <!--  <el-select v-model="formValue.companyId" placeholder="请选择" style="width: 100%;"  disabled>-->
              <!--    <el-option-->
              <!--      v-for="item in companyArr"-->
              <!--      :key="item.companyId"-->
              <!--      :label="item.companyName"-->
              <!--      :value="item.companyId">-->
              <!--    </el-option>-->
              <!--  </el-select>-->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_login_account')" prop="loginId">
              <el-input v-model="formValue.loginId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_name')" prop="name">
              <el-input v-model="formValue.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item :label="$tt('label_phone_number')">
              <el-input v-model="formValue.mobile"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_mailbox')">
              <el-input v-model="formValue.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item :label="$tt('label_employee_ID')">
              <el-input v-model="formValue.workNo"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <ex_header_spiler :title="$tt('label_permission_config')" v-if="roleScope != 'DEFAULT'"></ex_header_spiler>

        <el-row v-if="roleScope != 'DEFAULT'">
          <el-col :span="2">

            <div style="display: flex; padding-left: 20px; gap: 14px; line-height: 32px;">
              <div style="flex:1 ; text-align: left; font-weight: bold; ">{{ $tt('label_system_type') }}</div>
              <div style="width: 80px; font-weight: bold; text-align: center;  ">{{ $tt('label_enable_status') }}</div>
              <div style="width: 180px; text-align: center; font-weight: bold; ">{{ $tt('label_permission_level') }}</div>
              <div style="width: 200px; text-align: center; font-weight: bold;">{{ $tt('label_role_selection') }}</div>
            </div>

            <template v-if="formValue.companyId && companyRoleMap[formValue.companyId]">
              <div v-for="item, index in companyRoleMap[formValue.companyId]"
                style="display: flex; padding-left: 20px; line-height: 42px; gap: 14px;">
                <div style="flex:1 ; overflow-x: hidden; white-space: nowrap; text-overflow: ellipsis; overflow: hidden;">
                  {{ item.roleSystem == 'WMS' ? ('WMS - ' + item.warehouseName) : roleSystemMap[item.roleSystem] }}</div>
                <div style="width: 80px; text-align: center;  ">
                  <el-switch v-model="item.userRoleStatus" active-value="ENABLE" inactive-value="DISABLED">
                  </el-switch>
                </div>
                <div style="width: 180px;">
                  <el-select v-model="item.userRoleType" :placeholder="$tt('tip_please_select')" style="width: 100%;"
                    :disabled="item.userRoleStatus == 'DISABLED'">
                    <el-option key="ADMIN" :label="$tt('label_admin_user')" value="ADMIN"></el-option>
                    <el-option key="OPERATOR" :label="$tt('label_operator_user')" value="OPERATOR"></el-option>
                  </el-select>
                </div>
                <div style="width: 200px;">
                  <el-select v-model="item.userRoleId" :placeholder="$tt('tip_please_select')" style="width: 100%;"
                    :disabled="item.userRoleStatus == 'DISABLED' || item.userRoleType == 'ADMIN'">
                    <el-option v-for="item in item.children" :key="item.roleId" :label="item.roleName"
                      :value="item.roleId">
                    </el-option>
                  </el-select>
                </div>
              </div>
            </template>
          </el-col>


        </el-row>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $tt('label_cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $tt('label_confirm') }}</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script>

export default {

  title: 'title_user_manage',
  components: {},

  data() {

    let _this = this

    return {

      formModel: 'insert/update',

      roleSystemArr: [
        { id: 'WMS', name: this.$tt('label_wms_warehouse_system') },
        { id: 'TMS', name: this.$tt('label_tms_transport_system') },
        { id: 'OMS', name: this.$tt('label_business_back_system') }
      ],
      roleSystemMap: {},

      dialogFormVisible: false,
      dialogTitle: '',
      formValue: {},
      rules: {
        companyName: [
          { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
          { min: 3, max: 32, message: this.$tt('tip_length_in_min_max', { mim: 3, max: 32 }), trigger: 'blur' }
        ],
        companyShortCode: [
          { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
          { min: 3, max: 16, message: this.$tt('tip_length_in_min_max', { mim: 3, max: 16 }), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
          { min: 2, max: 16, message: this.$tt('tip_length_in_min_max', { mim: 2, max: 16 }), trigger: 'blur' }
        ],
        loginId: [
          { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
          {
            validator: (r, v, cb) => {
              if (!this.$reg.PureNumberLetterUnderline(v)) {
                return cb(this.$tt('tip_only_input_number_char_underline'))
              }
              cb()
            }, trigger: 'blur'
          },
        ]
      },

      companyArr: [],
      companyMap: {},
      // 货代公司的角色信息
      companyRoleMap: {
        "companyId": [{
          "roleSystem": "WMS",
          "children": [{
            "roleId": 11,
            "roleName": "role1"
          }, {
            "roleId": 22,
            "roleName": "role2"
          }]
        }]
      },

      userRoleMap: {},


      userCompanyDataArray: []

    };
  },


  watch: {
    'formValue.companyId'(val, old) {

    }
  },

  created() {

    let _this = this

    _this.roleSystemMap = {}
    _this.roleSystemArr.forEach(e => {
      _this.roleSystemMap[e.id] = e.name
    })

    // 加载所有货代公司
    _this.$ajax({
      url: '/ums-api/client/UserCompanyClientRpc/loadAllCompanyData.json',
      success: (res) => {

        _this.companyArr = res.data.rows

        if (res && res.data && res.data.rows) {
          _this.userCompanyDataArray = res.data.rows
          _this.filterUserRoleOptions()
        }

      }
    });



    _this.option = {
      search: {
        model: [
          { label: "label_keyword", key: "keyword", },
          {
            label: "label_status", key: "status", type: 'select', enum: 'UserStatusEnum'
          }
        ],
      },
      action: [
        {
          label: this.roleScope != 'DEFAULT' ? "label_add_user" : "label_add_admin", attrs: { icon: "el-icon-plus" }, click: () => {

            if (this.roleSystem == 'WMS') {
              this.filterUserRoleOptions()
            }

            // console.log

            this.formModel = 'insert'
            this.dialogTitle = this.$tt('label_add_user')
            if (this.roleScope == 'DEFAULT') {
              this.dialogTitle = this.$tt('label_add_admin')
            }
            this.dialogFormVisible = true
            this.formValue = {
              companyId: this.$currentAgentId
            }

            // console.log
          }
        },
      ],

      table: {
        url: "/ums-api/user/UserInfoClientRpc/list.json?roleSystem=" + this.roleSystem + "&roleScope=" + this.roleScope,
        attrs: {
          'cell-style': ({ row, column, rowIndex, columnIndex }) => {
            if (column.property == 'status') {
              return { color: row.status == 'NORMAL' ? this.$globalCss.successColor : this.$globalCss.infoColor }
            }
          }
        },
        model: [
          { key: 'loginId', label: 'label_login_account', align: 'left' },
          { key: 'name', label: 'label_user_name', align: 'left' },
          { key: 'companyName', label: 'label_belong_company', align: 'left', if: function () { return _this.roleScope != 'DEFAULT' } },
          {
            key: 'roleInfos', label: 'label_role_info', align: 'left', width: 300, if: function () { return _this.roleScope != 'DEFAULT' },
            attrs: {
              formatter: (r, c, v, i) => {
                if (v && v.length > 0) {

                  // OMS
                  if (this.roleSystem == 'OMS' || this.roleSystem == 'ALL') {

                    let arr = []

                    for (let iii = 0; iii < v.length; iii++) {
                      let tmpR = v[iii]
                      if (tmpR.userRoleStatus != 'ENABLE') {
                        continue
                      }

                      let str = tmpR.userRoleSystem == 'WMS' ? ('WMS - ' + tmpR.warehouseName) : this.roleSystemMap[tmpR.userRoleSystem]
                      str += " : " + (tmpR.userRoleType == 'ADMIN' ? this.$tt('label_admin_user') : tmpR.userRoleName)
                      arr.push(str)
                    }

                    return arr.join(',   ')
                  }
                  // TMS
                  else if (this.roleSystem == 'TMS') {
                    v = v.filter(ee => ee.userRoleStatus == 'ENABLE' && ee.userRoleSystem == 'TMS')
                    if (v && v.length > 0) {
                      let tmpR = v[0]
                      return tmpR.userRoleType == 'ADMIN' ? this.$tt('label_admin_user') : tmpR.userRoleName
                    }
                  }
                  // WMS
                  else if (this.roleSystem == 'WMS') {

                    v = v.filter(ee => ee.userRoleStatus == 'ENABLE' && ee.userRoleSystem == 'WMS')
                    for (let iii = 0; iii < v.length; iii++) {
                      let tmpR = v[iii]
                      if (this.$loginUser.currentWarehouseId == tmpR.warehouseId) {
                        return tmpR.userRoleType == 'ADMIN' ? this.$tt('label_admin_user') : tmpR.userRoleName
                      }
                    }
                  }
                }
                return ''
              }
            }
          },
          { key: 'mobile', label: 'label_phone_number', align: 'left', width: 120 },
          {
            key: 'status', label: 'label_status',
            width: 120,
            attrs: {
              formatter: (r, c, v, i) => { return this.$enumShow(v, 'UserStatusEnum') }
            }
          },
          { key: 'lastLoginTime', label: 'label_last_login_time', attrs: { formatter: (r, c, v, i) => { return this.$dateFormat(v) } } },
          {
            key: 'gmtCreate', label: 'label_create_time',
            attrs: {
              formatter: (r, c, v, i) => { return this.$dateFormat(v) }
            }
          },
          {
            type: 'operate', width: 220,
            operate: [
              {
                label: 'label_reset_password', type: "confirm-button", message: "tip_reset_password_confirm", url: '/ums-api/user/UserInfoClientRpc/resetPwd.json',
                params: (v) => { return { securityId: v.securityId } }, done: ['tip', (row, i, data, res) => { this.afterPwdReset(res) }]
              },
              {
                label: 'label_freeze', type: "confirm-button", message: "tip_freeze_user_confirm", url: '/ums-api/user/UserInfoClientRpc/freeze.json',
                if: (row) => { return row.status == 'NORMAL' },
                params: (v) => { return { securityId: v.securityId, type: 'freeze' } }, done: ['reload', 'tip'],
              },
              {
                label: 'label_unfreeze', type: "confirm-button", message: "tip_unfreeze_user_confirm", url: '/ums-api/user/UserInfoClientRpc/freeze.json',
                if: (row) => { return row.status != 'NORMAL' },
                params: (v) => { return { securityId: v.securityId, type: 'unfreeze' } }, done: ['reload', 'tip']
              },
              {
                label: 'label_edit', click: (row) => {

                  let _this = this

                  if (_this.roleSystem == 'WMS') {
                    this.filterUserRoleOptions()
                  }

                  this.formModel = 'update'
                  this.dialogTitle = this.$tt('label_edit_user')
                  if (this.roleScope == 'DEFAULT') {
                    this.dialogTitle = this.$tt('label_edit_admin')
                  }

                  // 角色表单填充
                  let roleFormArr = _this.companyRoleMap[row.companyId]
                  if (roleFormArr && row.roleInfos) {
                    let tmpCache = {}
                    row.roleInfos.forEach(rr => {
                      let k = rr.userRoleSystem + ((rr.warehouseId && rr.warehouseId != null) ? rr.warehouseId : '')
                      tmpCache[k] = {
                        userRoleType: rr.userRoleType,
                        userRoleId: rr.userRoleId,
                        userRoleStatus: rr.userRoleStatus
                      }
                    })

                    let tmpArr = []

                    roleFormArr.forEach(oldRow => {

                      let rr = { ...oldRow }

                      let k = rr.roleSystem + ((rr.warehouseId && rr.warehouseId != null) ? rr.warehouseId : '')

                      let tmpCacheObj = tmpCache[k]
                      if (tmpCacheObj) {
                        rr.userRoleType = tmpCacheObj.userRoleType ? tmpCacheObj.userRoleType : ''
                        rr.userRoleId = tmpCacheObj.userRoleId ? tmpCacheObj.userRoleId : ''
                        rr.userRoleStatus = tmpCacheObj.userRoleStatus ? tmpCache[k].userRoleStatus : 'DISABLED'
                      } else {
                        rr.userRoleType = ''
                        rr.userRoleId = ''
                        rr.userRoleStatus = 'DISABLED'
                      }

                      tmpArr.push(rr)

                    })

                    _this.companyRoleMap[row.companyId] = tmpArr
                    // // console.log
                  }

                  // delete row.roleInfos
                  this.formValue = JSON.parse(JSON.stringify(row))
                  this.dialogFormVisible = true


                  // console.log
                }
              },
              {
                label: 'label_delete', type: "confirm-button", url: '/ums-api/user/UserInfoClientRpc/delete.json', message: '确定要删除该记录吗？',
                params: (v) => { return { securityId: v.securityId } }, done: ['reload', 'tip']
              }
            ],
          }
        ]
      }
    }



  },

  props: {

    // admin  compnay
    'roleScope': {
      type: String,
      defafult: ''
    },

    // WMS OMS TMS
    'roleSystem': {
      type: String,
      defafult: ''
    }

  },

  destroyed() {

  },

  methods: {

    filterUserRoleOptions() {

      let _this = this
      let companyRoleMap = {}

      _this.userCompanyDataArray.forEach(rr => {

        _this.companyMap[rr.companyId] = rr

        companyRoleMap[rr.companyId] = []

        let companyRoleGroup = {}
        rr.roleList.forEach(role => {
          if (!companyRoleGroup[role.roleSystem]) {
            companyRoleGroup[role.roleSystem] = []
          }
          companyRoleGroup[role.roleSystem].push({
            "roleId": role.roleId,
            "roleName": role.roleName
          })

          _this.userRoleMap[role.roleId] = role.roleName
        })

        let warehouseChooseArr = []
        if (companyRoleGroup['WMS']) {

          let wmsRow = companyRoleGroup['WMS']

          delete companyRoleGroup['WMS']

          if (rr.warehouseList && rr.warehouseList.length > 0) {

            rr.warehouseList.forEach(wh => {
              let needAdd = false
              if (_this.roleSystem == 'ALL') {
                needAdd = true
              }
              else if (_this.roleSystem == 'WMS' && _this.$currentWarehouseId == wh.warehouseId) {
                needAdd = true
              }
              if (needAdd) {
                warehouseChooseArr.push({
                  "roleSystem": "WMS",
                  "warehouseId": wh.warehouseId,
                  "warehouseName": wh.warehouseName,
                  "warehouseCode": wh.warehouseCode,
                  "children": wmsRow
                })
              }

            })
          }
        }


        if (companyRoleGroup['OMS']) {
          companyRoleMap[rr.companyId].push({
            "roleSystem": 'OMS',
            "children": companyRoleGroup['OMS']
          })
        }
        if (companyRoleGroup['TMS']) {
          companyRoleMap[rr.companyId].push({
            "roleSystem": 'TMS',
            "children": companyRoleGroup['TMS']
          })
        }

        if (warehouseChooseArr.length > 0) {
          warehouseChooseArr.forEach(tmpR => {
            tmpR.userRoleType = ''
            tmpR.userRoleId = ''
            tmpR.userRoleStatus = 'DISABLED'
            companyRoleMap[rr.companyId].push(tmpR)
          })
        }

        if (_this.roleSystem != 'ALL') {
          companyRoleMap[rr.companyId] = companyRoleMap[rr.companyId].filter(eee => eee.roleSystem == _this.roleSystem)
        }
      })

      // console.log

      _this.companyRoleMap = companyRoleMap
    },

    afterPwdReset(res) {
      this.$alert(this.$tt('tip_account_new_password_reset_success', {
        account: res.data.loginId,
        password: res.data.pwd,
      }));
      // this.$alert('账号 ' + res.data.loginId + ' 的新密码为: ' + res.data.pwd, '密码重置成功',);
    },

    submitForm() {

      let _this = this

      _this.$refs['formEl'].validate((valid) => {
        if (valid) {

          if (this.roleScope != 'DEFAULT') {

            let tmpCompanyId = _this.formValue.companyId

            _this.formValue.companyName = _this.companyMap[tmpCompanyId].companyName
            _this.formValue.companyType = _this.companyMap[tmpCompanyId].companyType
            _this.formValue.roleSystem = _this.roleSystem

            let roleFormArr = _this.companyRoleMap[tmpCompanyId]

            // // console.log

            if (roleFormArr && roleFormArr.length > 0) {

              let submitRowData = []

              roleFormArr.forEach(tmpRole => {

                submitRowData.push({
                  userRoleType: tmpRole.userRoleType,
                  userRoleId: tmpRole.userRoleId,
                  userRoleName: _this.userRoleMap[tmpRole.userRoleId],
                  userRoleStatus: tmpRole.userRoleStatus,
                  userRoleSystem: tmpRole.roleSystem,
                  warehouseId: tmpRole.warehouseId,
                  warehouseCode: tmpRole.warehouseCode,
                  warehouseName: tmpRole.warehouseName
                })
              })
              _this.formValue.roleInfos = submitRowData
            }
          }

          _this.formValue.roleScope = _this.roleScope

          _this.$ajax({
            url: '/ums-api/user/UserInfoClientRpc/saveUpdate.json',
            type: 'json',
            data: _this.formValue,
            success: (responseData) => {
              this.$message({
                showClose: true,
                message: this.$tt('tip_submit_success'),
                type: 'success'
              })
              _this.$refs['superTablePage'].reload()
              _this.dialogFormVisible = false
            }
          });

        } else {
          return false;
        }

      });

    }


  }
};

</script>
<style>
.small-btn span {
  font-size: 14px;
}

.small-btn .el-button--small span {
  font-size: 14px;
}
</style>
